/**
 * 故事管理Store
 * 管理故事数据和操作
 * 已改造为使用Django后端API
 */

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useToast } from 'vue-toastification'
import apiClient from '@/api/axios'
import { API_ENDPOINTS, STORY_CATEGORIES } from '@/api/config'

export const useStoriesStore = defineStore('stories', () => {
  const toast = useToast()

  // ==================== State ====================
  const stories = ref([])
  const currentStory = ref(null)
  const isGenerating = ref(false)
  const categories = ref(STORY_CATEGORIES)

  // ==================== Getters ====================
  const publishedStories = computed(() => 
    stories.value.filter(story => story.status === 'published')
  )
  
  const draftStories = computed(() => 
    stories.value.filter(story => story.status === 'draft')
  )

  const getStoriesByCategory = computed(() => (category) => 
    publishedStories.value.filter(story => story.category === category)
  )

  const topStories = computed(() => 
    publishedStories.value
      .sort((a, b) => (b.likes + b.views) - (a.likes + a.views))
      .slice(0, 10)
  )

  // ==================== Actions ====================

  /**
   * AI生成故事
   * @param {string} prompt - 故事主题
   * @param {string} category - 故事分类
   * @param {number} wordCount - 字数
   */
  const generateStory = async (prompt, category = '奇幻', wordCount = 500) => {
    isGenerating.value = true
    
    try {
      const response = await apiClient.post(API_ENDPOINTS.STORY_GENERATE, {
        prompt,
        category,
        word_count: wordCount
      })
      
      if (response.success) {
        currentStory.value = response.data
        // 添加到本地列表
        stories.value.unshift(response.data)
        
        toast.success(response.message)
        return {
          success: true,
          story: response.data,
          message: response.message
        }
      }
      
      return response
    } catch (error) {
      toast.error(error.message || '故事生成失败')
      throw error
    } finally {
      isGenerating.value = false
    }
  }

  /**
   * 加载故事列表
   * @param {Object} params - 查询参数
   */
  const loadStories = async (params = {}) => {
    try {
      const response = await apiClient.get(API_ENDPOINTS.STORY_LIST, { params })
      
      if (response.success) {
        stories.value = response.data.items || []
      }
      
      return response
    } catch (error) {
      console.error('加载故事失败:', error)
      throw error
    }
  }

  /**
   * 获取故事详情
   * @param {number} storyId - 故事ID
   */
  const getStoryDetail = async (storyId) => {
    try {
      const response = await apiClient.get(API_ENDPOINTS.STORY_DETAIL(storyId))
      
      if (response.success) {
        currentStory.value = response.data
      }
      
      return response
    } catch (error) {
      console.error('获取故事详情失败:', error)
      throw error
    }
  }

  /**
   * 保存故事
   * @param {Object} story - 故事数据
   */
  const saveStory = async (story) => {
    try {
      let response
      
      if (story.id) {
        // 更新现有故事
        response = await apiClient.put(
          API_ENDPOINTS.STORY_UPDATE(story.id),
          story
        )
      } else {
        // 创建新故事
        response = await apiClient.post(API_ENDPOINTS.STORY_CREATE, story)
      }
      
      if (response.success) {
        // 更新本地数据
        const index = stories.value.findIndex(s => s.id === response.data.id)
        if (index >= 0) {
          stories.value[index] = response.data
        } else {
          stories.value.unshift(response.data)
        }
        
        toast.success(response.message)
      }
      
      return response
    } catch (error) {
      toast.error(error.message || '保存失败')
      throw error
    }
  }

  /**
   * 发布故事
   * @param {number} storyId - 故事ID
   */
  const publishStory = async (storyId) => {
    try {
      const response = await apiClient.post(API_ENDPOINTS.STORY_PUBLISH(storyId))
      
      if (response.success) {
        // 更新本地数据
        const story = stories.value.find(s => s.id === storyId)
        if (story) {
          story.status = 'published'
          story.published_at = response.data.published_at
        }
        
        toast.success(response.message)
      }
      
      return response
    } catch (error) {
      toast.error(error.message || '发布失败')
      throw error
    }
  }

  /**
   * 删除故事
   * @param {number} storyId - 故事ID
   */
  const deleteStory = async (storyId) => {
    try {
      const response = await apiClient.delete(API_ENDPOINTS.STORY_DELETE(storyId))
      
      if (response.success) {
        // 从本地列表移除
        const index = stories.value.findIndex(s => s.id === storyId)
        if (index >= 0) {
          stories.value.splice(index, 1)
        }
        
        toast.success(response.message)
      }
      
      return response
    } catch (error) {
      toast.error(error.message || '删除失败')
      throw error
    }
  }

  /**
   * 点赞故事
   * @param {number} storyId - 故事ID
   */
  const likeStory = async (storyId) => {
    try {
      const response = await apiClient.post(API_ENDPOINTS.STORY_LIKE(storyId))
      
      if (response.success) {
        // 更新本地数据
        const story = stories.value.find(s => s.id === storyId)
        if (story) {
          story.likes = response.data.likes
          story.is_liked = response.data.is_liked
        }
        
        // 更新当前故事
        if (currentStory.value?.id === storyId) {
          currentStory.value.likes = response.data.likes
          currentStory.value.is_liked = response.data.is_liked
        }
      }
      
      return response
    } catch (error) {
      toast.error(error.message || '操作失败')
      throw error
    }
  }

  /**
   * 添加评论
   * @param {number} storyId - 故事ID
   * @param {string} content - 评论内容
   */
  const addComment = async (storyId, content) => {
    try {
      const response = await apiClient.post(
        API_ENDPOINTS.COMMENT_ADD(storyId),
        { content }
      )
      
      if (response.success) {
        // 更新当前故事的评论
        if (currentStory.value?.id === storyId) {
          if (!currentStory.value.comments) {
            currentStory.value.comments = []
          }
          currentStory.value.comments.push(response.data)
        }
        
        toast.success(response.message)
      }
      
      return response
    } catch (error) {
      toast.error(error.message || '评论失败')
      throw error
    }
  }

  /**
   * 删除评论
   * @param {number} storyId - 故事ID
   * @param {number} commentId - 评论ID
   */
  const deleteComment = async (storyId, commentId) => {
    try {
      const response = await apiClient.delete(
        API_ENDPOINTS.COMMENT_DELETE(storyId, commentId)
      )
      
      if (response.success) {
        // 更新当前故事的评论
        if (currentStory.value?.id === storyId && currentStory.value.comments) {
          currentStory.value.comments = currentStory.value.comments.filter(
            c => c.id !== commentId
          )
        }
        
        toast.success(response.message)
      }
      
      return response
    } catch (error) {
      toast.error(error.message || '删除失败')
      throw error
    }
  }

  /**
   * 获取热门故事
   * @param {number} limit - 数量限制
   */
  const loadTopStories = async (limit = 10) => {
    try {
      const response = await apiClient.get(API_ENDPOINTS.STORY_TOP, {
        params: { limit }
      })
      
      if (response.success) {
        return response.data
      }
      
      return []
    } catch (error) {
      console.error('加载热门故事失败:', error)
      return []
    }
  }

  /**
   * 搜索故事
   * @param {string} keyword - 搜索关键词
   */
  const searchStories = async (keyword) => {
    try {
      const response = await apiClient.get(API_ENDPOINTS.STORY_LIST, {
        params: { search: keyword }
      })
      
      if (response.success) {
        stories.value = response.data.items || []
      }
      
      return response
    } catch (error) {
      console.error('搜索故事失败:', error)
      throw error
    }
  }

  /**
   * 按分类加载故事
   * @param {string} category - 分类
   */
  const loadStoriesByCategory = async (category) => {
    try {
      const response = await apiClient.get(API_ENDPOINTS.STORY_LIST, {
        params: { category }
      })
      
      if (response.success) {
        stories.value = response.data.items || []
      }
      
      return response
    } catch (error) {
      console.error('加载分类故事失败:', error)
      throw error
    }
  }

  // ==================== Return ====================
  return {
    // State
    stories,
    currentStory,
    isGenerating,
    categories,
    
    // Getters
    publishedStories,
    draftStories,
    getStoriesByCategory,
    topStories,
    
    // Actions
    generateStory,
    loadStories,
    getStoryDetail,
    saveStory,
    publishStory,
    deleteStory,
    likeStory,
    addComment,
    deleteComment,
    loadTopStories,
    searchStories,
    loadStoriesByCategory
  }
})
